<?php

namespace App\Http\Controllers\School;

use App\Http\Requests\School\EditBookRulePrice;
use App\Http\Requests\School\StoreBookRulePrice;
use App\Http\Resources\School\BookRulePriceResource;
use App\Models\BookRule;
use App\Models\BookRulePrice;
use App\Models\PriceCategory;
use App\Models\SchoolAdminLog;

/**
 *
 * 订餐价格规则管理
 *
 * Class BookRulePriceController
 * @package App\Http\Controllers\School
 */
class BookRulePriceController extends BaseController
{
    /**
     * @param StoreBookRulePrice $request
     * @return BookRulePriceResource|array
     * 新增订餐规则价格
     */
    public function store(StoreBookRulePrice $request)
    {
        $bookRule = BookRule::where('school_id', \Auth::user()->school_id)->findOrFail($request->rule_id);
        $bookRulePrice = BookRulePrice::create($request->all());
        $eatDate = $bookRule->eat_date;
        $eatType = $bookRule->getTypeLabelAttribute();
        SchoolAdminLog::Log('添加计费条目: ' . $eatDate . ' - ' . $eatType . ', '
            . PriceCategory::where('school_id', \Auth::user()->school_id)->where('status', 1)->where('id', $request->category_id)->first(['name'])->name
            . ' - ' . $request->total_price . '元');
        return new BookRulePriceResource($bookRulePrice);
    }

    /**
     * @param EditBookRulePrice $request
     * @param BookRulePrice $bookRulePrice
     * @return BookRulePriceResource|array
     * 编辑订餐规则价格
     */
    public function update(EditBookRulePrice $request, BookRulePrice $bookRulePrice)
    {
        $bookRule = BookRule::where('school_id', \Auth::user()->school_id)->findOrFail($request->rule_id);
        $bookRulePrice->fill($request->all());
        $bookRulePrice->save();
        $eatDate = $bookRule->eat_date;
        $eatType = $bookRule->getTypeLabelAttribute();
        SchoolAdminLog::Log('修改计费条目: ' . $eatDate . ' - ' . $eatType . ', '
            . PriceCategory::where('school_id', \Auth::user()->school_id)->where('status', 1)->where('id', $request->category_id)->first(['name'])->name
            . ' - ' . $request->total_price . '元');
        return new BookRulePriceResource($bookRulePrice);
    }

    /**
     * @param BookRulePrice $bookRulePrice
     * @return BookRulePriceResource
     * @throws \Exception
     * 删除订餐规则价格
     */
    public function destroy(BookRulePrice $bookRulePrice)
    {
        $bookRulePrice->delete();
        SchoolAdminLog::Log('删除计费条目: id - ' . $bookRulePrice->id);
        return new BookRulePriceResource($bookRulePrice);
    }
}
